<template>
  <div class="cart-page">
    <h2 style="margin-bottom: 24px;">我的购物车</h2>
    <el-table :data="cartList" style="width: 100%" v-loading="loading" empty-text="购物车为空" @selection-change="handleSelectionChange" ref="cartTable">
      <el-table-column type="selection" width="55" />
      <el-table-column label="图片" width="80">
        <template #default="scope">
          <img :src="fullImg(scope.row.product.cover_image)" style="width:60px;height:60px;object-fit:cover;border-radius:8px;" />
        </template>
      </el-table-column>
      <el-table-column prop="product.name" label="商品" min-width="120" />
      <el-table-column prop="product.price" label="单价" width="80" />
      <el-table-column label="数量" width="150">
        <template #default="scope">
          <div style="display: flex; align-items: center; justify-content: center;">
            <el-button
              size="small"
              @click="handleMinus(scope)"
              :disabled="scope.row.quantity <= 0"
              style="margin-right: 4px;"
              circle
            >
              <el-icon><Minus /></el-icon>
            </el-button>
            <el-input
              v-model="scope.row.quantity"
              type="number"
              min="0"
              :max="scope.row.product.detail?.stock ?? 1"
              @change="val => updateCartQuantity(scope.row.id, Number(val))"
              style="width: 60px; text-align: center;"
            />
            <el-button
              size="small"
              @click="handleCustomPlus(scope)"
              :disabled="scope.row.quantity >= (scope.row.product.detail?.stock ?? 1)"
              style="margin-left: 4px;"
              circle
            >
              <el-icon><Plus /></el-icon>
            </el-button>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="总价" width="100">
        <template #default="scope">
          ￥{{ (scope.row.product.price * scope.row.quantity).toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button
            type="success"
            size="small"
            @click="payForCartItem(scope.row)"
          >
            支付
          </el-button>
          <el-button type="danger" size="small" @click="removeCartItem(scope.row.id)">移除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div v-if="cartList.length" style="text-align:right;margin-top:24px;">
      <span style="font-size:1.2rem;margin-right:24px;">总计：￥{{ totalPrice }}</span>
      <el-button type="success" @click="checkout">结算</el-button>
      <el-button type="danger" @click="removeAllCartItems" style="margin-left:12px;">全部移除</el-button>
      <el-button type="primary" @click="payAllCartItems" style="margin-left:12px;">全部支付</el-button>
      <el-button
        type="danger"
        :disabled="!selectedItems.length"
        @click="removeSelectedCartItems"
        style="margin-left:12px;"
      >
        删除选中
      </el-button>
      <el-button
        type="primary"
        :disabled="selectedItems.length < 2"
        @click="paySelectedCartItems"
        style="margin-left:12px;"
      >
        支付选中
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue'
import request from '@/utils/request'
import { useUserStore } from '../stores/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Minus } from '@element-plus/icons-vue'

const userStore = useUserStore()
const cartList = ref([])
const loading = ref(false)
const selectedItems = ref([])
const cartTable = ref(null)
// 记录每个cart item的上一次数量
const lastQuantityMap = ref({})

function fullImg(url) {
  return url && url.startsWith('http') ? url : `http://127.0.0.1:8000/media${url}`
}

const fetchCartList = async () => {
  loading.value = true
  const res = await request.get('/shop/cart/', {
    params: { userid: userStore.userid }
  })
  cartList.value = res.carts || []
  loading.value = false
}

async function removeCartItem(cartid) {
  const res = await request.delete('/shop/cart/', {
    data: { cartid }
  })
  if (res.code === 200) {
    ElMessage.success('已移除')
    fetchCartList()
  }
}

async function updateCartQuantity(cartid, quantity) {
  // 找到对应的cart item
  const cartItem = cartList.value.find(item => item.id === cartid)
  if (!cartItem) return
  const stock = cartItem.product.detail?.stock ?? 0
  const oldQuantity = lastQuantityMap.value[cartid] ?? cartItem.quantity
  // 超过库存
  if (quantity > stock) {
    ElMessage.warning('不能超过库存数量')
    cartItem.quantity = stock
    return
  }
  // 数量为0，弹窗确认
  if (quantity <= 0) {
    ElMessageBox.confirm('数量为0，是否移出购物车？', '确认移除', {
      confirmButtonText: '移除',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      await removeCartItem(cartid)
    }).catch(() => {
      // 恢复为弹窗前的数量
      cartItem.quantity = oldQuantity
    })
    return
  }
  // 正常更新
  const res = await request.patch('/shop/cart/', {
    cartid,
    quantity
  })
  if (res.code === 200) {
    //ElMessage.success('数量已更新') // 移除普通数量更新的提示
    fetchCartList()
  }
  // 记录本次数量
  lastQuantityMap.value[cartid] = quantity
}

const totalPrice = computed(() => {
  return cartList.value.reduce((sum, item) => sum + item.product.price * item.quantity, 0).toFixed(2)
})

function checkout() {
  ElMessage.success('请在商品详情页单独结算每个商品')
  // 可扩展为批量下单/支付
}

async function payForCartItem(item) {
  const res = await request.post('/shop/alipay/order/', {
    userid: userStore.userid,
    goodsid: item.product.id,
    quantity: item.quantity
  })
  if (res.code === 0 && res.pay_url && res.pay_url.startsWith('https://openapi-sandbox.dl.alipaydev.com/gateway.do')) {
    window.location.href = res.pay_url
  } else if (res.code === 3 && res.order_no) {
    ElMessageBox.confirm('5秒内已下单该商品，是否继续支付？', '提示', {
      confirmButtonText: '继续支付',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      const payRes = await request.post('/shop/alipay/order/', { order_no: res.order_no })
      if (payRes.code === 0 && payRes.pay_url) {
        window.location.href = payRes.pay_url
      }
    })
  } else {
    ElMessage.error(res.msg || '支付失败')
  }
}



async function removeAllCartItems() {
  const ids = cartList.value.map(item => item.id)
  for (const id of ids) {
    await removeCartItem(id)
  }
  ElMessage.success('已全部移除')
}



async function payAllCartItems() {
  if (!cartList.value.length) {
    ElMessage.warning('购物车为空');
    return;
  }
  // 这里假设后端支持批量支付，传递所有商品id和数量
  const res = await request.post('/shop/cart/pay/', {
    userid: userStore.userid,
    items: cartList.value.map(item => ({
      goodsid: item.product.id,
      quantity: item.quantity
    }))
  });
  if (res.code === 0 && res.pay_url) {
    window.location.href = res.pay_url; // 跳转支付宝沙箱
  } else {
    ElMessage.error(res.msg || '支付失败');
  }
}

function handleSelectionChange(selection) {
  selectedItems.value = selection
}

async function removeSelectedCartItems() {
  for (const item of selectedItems.value) {
    await removeCartItem(item.id)
  }
  ElMessage.success('已删除选中商品')
  selectedItems.value = []
  fetchCartList()
}

// 购物车批量支付
async function paySelectedCartItems() {
  if (!selectedItems.value.length) {
    ElMessage.warning('请选择要支付的商品')
    return
  }
  if (selectedItems.value.length === 1) {
    ElMessage.warning('请至少选择两件商品进行批量支付')
    return
  }
  const items = selectedItems.value.map(item => ({
    goodsid: item.product.id,
    quantity: item.quantity
  }))
  const res = await request.post('/shop/cart/pay/', {
    userid: userStore.userid,
    items
  })
  if (res.code === 0 && res.pay_url && res.pay_url.startsWith('https://openapi-sandbox.dl.alipaydev.com/gateway.do')) {
    window.location.href = res.pay_url
  } else {
    ElMessage.error(res.msg || '支付失败')
  }
}

// 新增方法
function handleCustomPlus(scope) {
  const stock = scope.row.product.detail?.stock ?? 1
  if (scope.row.quantity >= stock) {
    ElMessage.warning('库存不足')
    return
  }
  scope.row.quantity += 1
  updateCartQuantity(scope.row.id, scope.row.quantity)
}

function handleMinus(scope) {
  if (scope.row.quantity > 0) {
    scope.row.quantity -= 1
    updateCartQuantity(scope.row.id, scope.row.quantity)
  }
}

onMounted(() => {
  fetchCartList()
})

// 监听页面激活事件，检查是否需要刷新购物车
const handleVisibilityChange = () => {
  if (!document.hidden) {
    const refreshCart = localStorage.getItem('refreshCart')
    if (refreshCart === 'true') {
      localStorage.removeItem('refreshCart')
      fetchCartList()
    }
  }
}

onMounted(() => {
  fetchCartList()
  document.addEventListener('visibilitychange', handleVisibilityChange)
})

// 清理事件监听器
onUnmounted(() => {
  document.removeEventListener('visibilitychange', handleVisibilityChange)
})
</script>

<style scoped>
.cart-page {
  max-width: 900px;
  margin: 40px auto;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 2px 16px rgba(0,0,0,0.08);
  padding: 32px 24px;
}
</style> 